import { initParticlesJS } from '../particles.js'

// 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            //粒子效果
            initParticlesJS();

            // 检查用户登录状态并更新界面
            updateUserInterface();

            // 加载购物车数据
            loadCart();

            // 加载推荐商品
            loadRecommendedProducts();

            // 设置交互功能
            setupInteractions();

            // 移动菜单切换
            document.getElementById('mobile-menu-btn').addEventListener('click', function() {
                const mobileMenu = document.getElementById('mobile-menu');
                if (mobileMenu.classList.contains('hidden')) {
                    mobileMenu.classList.remove('hidden');
                } else {
                    mobileMenu.classList.add('hidden');
                }
            });
        });

        // 更新用户界面
        function updateUserInterface() {
            const user = localStorage.getItem('currentUser') ? JSON.parse(localStorage.getItem('currentUser')) : null;
            const authSection = document.getElementById('user-auth-section');
            const infoSection = document.getElementById('user-info-section');
            
            if (user) {
                authSection.classList.add('hidden');
                infoSection.classList.remove('hidden');
                document.getElementById('username').textContent = user.username;
                document.getElementById('user-avatar').src = user.avatar || 'https://picsum.photos/40/40';

                // 退出登录
                document.getElementById('logout-btn').addEventListener('click', function() {
                    localStorage.removeItem('currentUser');
                    window.location.reload();
                });
            } else {
                authSection.classList.remove('hidden');
                infoSection.classList.add('hidden');
            }

            // 更新购物车数量
            updateCartCount();
        }

        // 更新购物车数量
        function updateCartCount() {
            const cart = localStorage.getItem('cart') ? JSON.parse(localStorage.getItem('cart')) : [];
            const cartCount = document.getElementById('cart-count');
            cartCount.textContent = cart.length;
        }

        // 加载购物车数据
        function loadCart() {
            const cart = localStorage.getItem('cart') ? JSON.parse(localStorage.getItem('cart')) : [];
            const emptyCart = document.getElementById('empty-cart');
            const cartContent = document.getElementById('cart-content');
            const cartItems = document.getElementById('cart-items');
            
            if (cart.length === 0) {
                emptyCart.classList.remove('hidden');
                cartContent.classList.add('hidden');
                return;
            } else {
                emptyCart.classList.add('hidden');
                cartContent.classList.remove('hidden');
            }
            
            let totalPrice = 0;
            cartItems.innerHTML = '';
            
            cart.forEach(item => {
                const itemTotal = item.price * item.quantity;
                totalPrice += itemTotal;
                
                const itemElement = document.createElement('div');
                itemElement.className = 'flex flex-col md:flex-row items-center p-4 md:py-6';
                itemElement.innerHTML = `
                    <div class="w-full md:w-2/5 flex items-center mb-4 md:mb-0">
                        <img src="${item.image}" alt="${item.name}" class="w-16 h-16 object-cover rounded mr-4">
                        <div>
                            <h3 class="font-medium">${item.name}</h3>
                            <p class="text-sm text-gray-500">规格：标准版</p>
                        </div>
                    </div>
                    <div class="w-full md:w-1/5 text-center mb-4 md:mb-0">
                        <span class="text-red-600 font-medium">¥${item.price.toFixed(2)}</span>
                    </div>
                    <div class="w-full md:w-1/5 flex items-center justify-center mb-4 md:mb-0">
                        <div class="flex items-center">
                            <button class="quantity-btn decrease-btn px-3 py-1 border border-gray-300 rounded-l-md hover:bg-gray-100" data-id="${item.id}">-</button>
                            <input type="number" value="${item.quantity}" min="1" class="item-quantity w-12 px-2 py-1 border-t border-b border-gray-300 text-center focus:outline-none" data-id="${item.id}" readonly>
                            <button class="quantity-btn increase-btn px-3 py-1 border border-gray-300 rounded-r-md hover:bg-gray-100" data-id="${item.id}">+</button>
                        </div>
                    </div>
                    <div class="w-full md:w-1/5 flex items-center justify-between md:justify-center">
                        <span class="text-red-600 font-bold md:mr-4">¥${itemTotal.toFixed(2)}</span>
                        <button class="remove-item text-gray-400 hover:text-red-500" data-id="${item.id}">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                `;
                cartItems.appendChild(itemElement);
            });
            
            // 更新总价
            document.getElementById('cart-total').textContent = `¥${totalPrice.toFixed(2)}`;
            
            // 添加数量按钮事件
            const decreaseBtns = document.querySelectorAll('.decrease-btn');
            const increaseBtns = document.querySelectorAll('.increase-btn');
            const removeButtons = document.querySelectorAll('.remove-item');
            
            decreaseBtns.forEach(button => {
                button.addEventListener('click', function() {
                    const id = parseInt(this.getAttribute('data-id'));
                    updateItemQuantity(id, -1);
                });
            });
            
            increaseBtns.forEach(button => {
                button.addEventListener('click', function() {
                    const id = parseInt(this.getAttribute('data-id'));
                    updateItemQuantity(id, 1);
                });
            });
            
            removeButtons.forEach(button => {
                button.addEventListener('click', function() {
                    const id = parseInt(this.getAttribute('data-id'));
                    removeFromCart(id);
                });
            });
        }

        // 更新商品数量
        function updateItemQuantity(id, change) {
            let cart = JSON.parse(localStorage.getItem('cart') || '[]');
            const itemIndex = cart.findIndex(item => item.id === id);
            
            if (itemIndex !== -1) {
                let newQuantity = cart[itemIndex].quantity + change;
                
                // 确保数量不小于1
                if (newQuantity < 1) {
                    newQuantity = 1;
                }
                
                cart[itemIndex].quantity = newQuantity;
                localStorage.setItem('cart', JSON.stringify(cart));
                
                // 更新显示
                document.querySelector(`.item-quantity[data-id="${id}"]`).value = newQuantity;
                
                // 重新加载购物车以更新总价和小计
                loadCart();
            }
        }

        // 从购物车移除商品
        function removeFromCart(id) {
            let cart = JSON.parse(localStorage.getItem('cart') || '[]');
            cart = cart.filter(item => item.id !== id);
            localStorage.setItem('cart', JSON.stringify(cart));
            
            // 更新购物车数量
            updateCartCount();
            
            // 重新加载购物车
            loadCart();
            
            // 显示通知
            showNotification('商品已从购物车移除');
        }

        // 清空购物车
        function clearCart() {
            localStorage.setItem('cart', '[]');
            
            // 更新购物车数量
            updateCartCount();
            
            // 重新加载购物车
            loadCart();
            
            // 显示通知
            showNotification('购物车已清空');
        }

        // 加载推荐商品
        function loadRecommendedProducts() {
            // 从localStorage获取商品数据，或者使用模拟数据
            let products = localStorage.getItem('products') ? JSON.parse(localStorage.getItem('products')) : [];
            
            if (products.length === 0) {
                // 如果没有商品数据，使用模拟数据
                products = [
                    {
                        id: 1,
                        name: '专业碳素鱼竿',
                        price: 299,
                        originalPrice: 399,
                        image: 'https://picsum.photos/400/300?rod',
                        category: 'rods',
                        featured: true
                    },
                    {
                        id: 2,
                        name: '金属轴承渔轮',
                        price: 199,
                        originalPrice: 259,
                        image: 'https://picsum.photos/400/300?reel',
                        category: 'reels',
                        featured: true
                    },
                    {
                        id: 3,
                        name: '仿生软饵套装',
                        price: 89,
                        originalPrice: 119,
                        image: 'https://picsum.photos/400/300?bait',
                        category: 'lures',
                        featured: true
                    },
                    {
                        id: 4,
                        name: '多功能钓箱',
                        price: 359,
                        originalPrice: 459,
                        image: 'https://picsum.photos/400/300?box',
                        category: 'accessories',
                        featured: true
                    }
                ];
            }
            
            // 随机选择4个商品作为推荐
            const recommended = products.sort(() => 0.5 - Math.random()).slice(0, 4);
            const container = document.getElementById('recommended-products');
            container.innerHTML = '';
            
            recommended.forEach(product => {
                const productElement = document.createElement('div');
                productElement.className = 'bg-white rounded-lg shadow-md overflow-hidden hover:shadow-xl transition duration-300 transform hover:-translate-y-1';
                productElement.innerHTML = `
                    <div class="relative">
                        <img src="${product.image}" alt="${product.name}" class="w-full h-48 object-cover cursor-pointer product-image" data-id="${product.id}">
                    </div>
                    <div class="p-4">
                        <h3 class="font-bold text-lg mb-1 cursor-pointer product-name" data-id="${product.id}">${product.name}</h3>
                        <div class="flex items-center mb-2">
                            <div class="flex text-yellow-400 text-sm mr-1">
                                <i class="fas fa-star"></i>
                                <i class="fas fa-star"></i>
                                <i class="fas fa-star"></i>
                                <i class="fas fa-star"></i>
                                <i class="fas fa-star-half-alt"></i>
                            </div>
                            <span class="text-xs text-gray-500">(${Math.floor(Math.random() * 200) + 50})</span>
                        </div>
                        <div class="flex justify-between items-center">
                            <div>
                                <span class="text-red-600 font-bold">¥${product.price}.00</span>
                                <span class="text-gray-500 text-sm line-through ml-1">¥${product.originalPrice}.00</span>
                            </div>
                            <button class="add-to-cart bg-blue-500 hover:bg-blue-600 text-white px-3 py-1 rounded text-sm transition duration-300" data-id="${product.id}">
                                加入购物车
                            </button>
                        </div>
                    </div>
                `;
                container.appendChild(productElement);
            });
            
            // 添加购物车按钮点击事件
            const addToCartButtons = document.querySelectorAll('.add-to-cart');
            addToCartButtons.forEach(button => {
                button.addEventListener('click', function() {
                    const productId = parseInt(this.getAttribute('data-id'));
                    addToCart(productId);
                });
            });
        }

        // 添加商品到购物车
        function addToCart(productId) {
            // 从localStorage获取商品数据
            let products = localStorage.getItem('products') ? JSON.parse(localStorage.getItem('products')) : [];
            
            if (products.length === 0) {
                // 如果没有商品数据，使用模拟数据
                products = [
                    {
                        id: 1,
                        name: '专业碳素鱼竿',
                        price: 299,
                        originalPrice: 399,
                        image: 'https://picsum.photos/400/300?rod'
                    },
                    {
                        id: 2,
                        name: '金属轴承渔轮',
                        price: 199,
                        originalPrice: 259,
                        image: 'https://picsum.photos/400/300?reel'
                    },
                    {
                        id: 3,
                        name: '仿生软饵套装',
                        price: 89,
                        originalPrice: 119,
                        image: 'https://picsum.photos/400/300?bait'
                    },
                    {
                        id: 4,
                        name: '多功能钓箱',
                        price: 359,
                        originalPrice: 459,
                        image: 'https://picsum.photos/400/300?box'
                    }
                ];
            }
            
            const product = products.find(p => p.id === productId);
            
            if (product) {
                // 获取当前购物车
                let cart = localStorage.getItem('cart') ? JSON.parse(localStorage.getItem('cart')) : [];
                
                // 检查商品是否已在购物车中
                const existingItemIndex = cart.findIndex(item => item.id === product.id);
                
                if (existingItemIndex !== -1) {
                    // 更新数量
                    cart[existingItemIndex].quantity += 1;
                } else {
                    // 添加新商品
                    cart.push({
                        id: product.id,
                        name: product.name,
                        price: product.price,
                        image: product.image,
                        quantity: 1
                    });
                }
                
                // 保存购物车
                localStorage.setItem('cart', JSON.stringify(cart));
                
                // 更新购物车数量
                updateCartCount();
                
                // 重新加载购物车
           loadCart();
                
                // 显示通知
                showNotification('商品已添加到购物车');
            }
        }

        // 设置交互功能
        function setupInteractions() {
            // 清空购物车按钮
            const clearCartBtn = document.getElementById('clear-cart');
            const confirmClearModal = document.getElementById('confirm-clear-modal');
            const cancelClearBtn = document.getElementById('cancel-clear');
            const confirmClearBtn = document.getElementById('confirm-clear');
            
            clearCartBtn.addEventListener('click', function() {
                confirmClearModal.classList.remove('hidden');
            });
            
            cancelClearBtn.addEventListener('click', function() {
                confirmClearModal.classList.add('hidden');
            });
            
            confirmClearBtn.addEventListener('click', function() {
                clearCart();
                confirmClearModal.classList.add('hidden');
            });
            
            // 结算按钮
            const checkoutBtn = document.getElementById('checkout-btn');
            const checkoutModal = document.getElementById('checkout-modal');
            const closeCheckoutModalBtn = document.getElementById('close-checkout-modal');
            
            checkoutBtn.addEventListener('click', function() {
                checkoutModal.classList.remove('hidden');
            });
            
            closeCheckoutModalBtn.addEventListener('click', function() {
                checkoutModal.classList.add('hidden');
            });
        }

        // 显示通知
        function showNotification(message) {
            const notification = document.getElementById('notification');
            notification.textContent = message;
            notification.classList.remove('hidden');
            notification.classList.remove('translate-y-20', 'opacity-0');
            
            setTimeout(() => {
                notification.classList.add('translate-y-20', 'opacity-0');
                setTimeout(() => {
                    notification.classList.add('hidden');
                }, 300);
            }, 2000);
        }